/* ***** BEGIN LICENSE BLOCK *****
 *   Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 * 
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Save File to.
 *
 * The Initial Developer of the Original Code is
 * Atte Kemppilä.
 * Portions created by the Initial Developer are Copyright (C) 2009
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 * 
 * ***** END LICENSE BLOCK ***** */


var EXPORTED_SYMBOLS =
[
    "callLater",
    "commonPrefix",
    "compare",
    "extend",
    "getNamedDirectory",
    "getPref",
    "isArray",
    "lazyInit",
    "ListenerManager",
    "PATH_DELIM",
    "Set",
    "setPref",
    "StringBundle",
    "TOPIC_PREF_CHANGED"
];


const Cc = Components.classes;
const Ci = Components.interfaces;
const Cu = Components.utils;

const dirSvc = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties);
const bundleSvc = Cc["@mozilla.org/intl/stringbundle;1"].getService(Ci.nsIStringBundleService);
const xulRuntime = Cc["@mozilla.org/xre/app-info;1"].getService(Ci.nsIXULRuntime);

const PATH_DELIM = ((xulRuntime.OS == "WINNT") ? "\\" : "/");

const TOPIC_PREF_CHANGED = "nsPref:changed";


// https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Inheritance
function extend(child, supertype)
{
    child.prototype.__proto__ = supertype.prototype;
}

function lazyInit(obj, name, value)
{
    delete obj[name];
    obj[name] = value;
    return value;
}

function isArray(arr)
{
    return (Object.prototype.toString.call(arr) === "[object Array]");
}

function compare(a, b)
{
    return a.compareTo(b);
}

function commonPrefix(a, b)
{
    var i = 0;
    var n = Math.min(a.length, b.length);
    while ((i < n) && (a[i] == b[i]))
        i++;
    
    return a.substr(0, i);
}

function callLater(delay, obj, func, args)
{
    if (typeof(func) != "function")
        throw new Error("callLater: function is not function: " + func);
    
    if (! ((args == undefined) || isArray(args)))
        throw new Error("callLater: args is not an Array: " + args);
    
    var timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
    var callback = {notify: function() { func.apply(obj, args); }}
    timer.initWithCallback(callback, delay, Ci.nsITimer.TYPE_ONE_SHOT);
    return timer;
}

function getNamedDirectory(name)
{
    try
    {
        return dirSvc.get(name, Ci.nsILocalFile);
    }
    catch (e)
    {
        Cu.reportError(e);
        return null;
    }
}

function getPref(branch, name, defaultValue)
{
    switch (branch.getPrefType(name))
    {
        case Ci.nsIPrefBranch.PREF_BOOL:
            return branch.getBoolPref(name);
        case Ci.nsIPrefBranch.PREF_INT:
            return branch.getIntPref(name);
        case Ci.nsIPrefBranch.PREF_STRING:
            return branch.getComplexValue(name, Ci.nsISupportsString).data;
        case Ci.nsIPrefBranch.PREF_INVALID:
            if (defaultValue !== undefined)
                return defaultValue;
            // fall-through
        default:
            throw new Error("unknown pref type: " + branch.getPrefType(name) + " (" + branch.root + name + ")");
    }
}

function setPref(branch, name, value)
{
    switch (branch.getPrefType(name))
    {
        case Ci.nsIPrefBranch.PREF_BOOL:
            branch.setBoolPref(name, value);
            break;
        case Ci.nsIPrefBranch.PREF_INT:
            branch.setIntPref(name, value);
            break;
        case Ci.nsIPrefBranch.PREF_STRING:
            var str = Cc["@mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString);
            str.data = value;
            branch.setComplexValue(name, Ci.nsISupportsString, str);
            break;
        default:
            throw new Error("unknown pref type: " + branch.getPrefType(name) + " (" + branch.root + name + ")");
    }
}


function Set(arr)
{
    for each (var value in arr)
        this[value] = true;
}


// nsIStringBundle
function StringBundle(url)
{
    this.bundle = bundleSvc.createBundle(url);
}

StringBundle.prototype =
{
    GetStringFromName: function(name)
    {
        try       { return this.bundle.GetStringFromName(name); }
        catch (e) { return name; }
    }
}


function ListenerManager()
{
    // empty
}

ListenerManager.prototype =
{
    addListener: function(callback)
    {
        if (! this._listeners)
            this._listeners = [];
        var index = this._listeners.indexOf(callback);
        if (index == -1)
            this._listeners.push(callback);
        return callback;
    },
    
    removeListener: function(callback)
    {
        var index = (this._listeners ? this._listeners.indexOf(callback) : -1);
        var found = (index != -1);
        if (found)
            this._listeners.splice(index, 1);
        return found;
    },
    
    notifyListeners: function(/* args... */)
    {
        if (this._listeners)
            for each (var callback in this._listeners)
                try
                {
                    callback.apply(null, arguments);
                }
                catch (e)
                {
                    Cu.reportError(e);
                }
    }
}
